﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core.Data;
using System.Text;
using System.Collections.Specialized;
namespace Lion.WeiXin
{
    public class LogFilterAttribute:ActionFilterAttribute
    {
        string _Description;
        string _paramNames;
        OperateLogTypeEnum _logType;
        DBContext db = new DBContext();
        /// <summary>
        /// 默认记录操作日志
        /// </summary>
        /// <param name="description">操作描述</param>
        public LogFilterAttribute(string description)
        {
            this._Description = description;
            this._logType = OperateLogTypeEnum.操作日志;
            this._paramNames = string.Empty;
        }
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="description">日志描述</param>
        /// <param name="logType">日志类型</param>
        /// <param name="paramNames">记录日志参数，多个逗号分隔</param>
        public LogFilterAttribute(string description, OperateLogTypeEnum logType= OperateLogTypeEnum.操作日志,string paramNames="" )
        {
            this._Description = description;
            this._logType = logType;
            this._paramNames = paramNames;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //访问url
            string visitUrl = HttpContext.Current.Request.RawUrl;
           // visitUrl = HttpContext.Current.Server.UrlEncode(visitUrl);
            //访问IPadress
            string ipAdress = HttpContext.Current.Request.UserHostAddress;

            //自动获取传递的参数
             StringBuilder builder = new StringBuilder();
            builder.Append("参数:");
            Dictionary<string, string> parmsObj = new Dictionary<string, string>();

            foreach (var item in this._paramNames.Split(',', '|'))
            {
                var valueProviderResult = filterContext.Controller.ValueProvider.GetValue(item);

                if (valueProviderResult != null && !parmsObj.ContainsKey(item))
                {
                    parmsObj.Add(item, valueProviderResult.AttemptedValue);
                }
            }
            //日志内容
            foreach (KeyValuePair<string, string> kvp in parmsObj)
            {
                builder.AppendFormat("{0}:{1} ", kvp.Key, kvp.Value);
            }
            if (parmsObj.Count == 0)
            {
                builder.Append("无");
            }

            //入库
            OperateLogModel model = new OperateLogModel();
            model.Creator = CurrentUser.UserName;
            model.Description = this._Description;
            model.LogType = this._logType.ToString();
            model.IpAdress = ipAdress;
            model.Parameter = builder.ToString();
            model.VisitUrl = visitUrl;
            db.Logs.Add(model);

        }
    }
}